package com.jinlejia.erp.ui.customer;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.HouseSelectAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.ActivityHasChectedBinding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.ActivityCollector;
import com.jinlejia.erp.utils.DataFilter;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 已选
 */
public class HasChectedActivity extends AppCompatActivity {

    private HouseSelectAdapter adapter;
    ArrayList<Map<String, Object>> sData = new ArrayList<>();
    ProgressDialog progressDialog;
    private ActivityHasChectedBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_has_chected);
        binding.btBack.setOnClickListener(this::onClick);
        binding.btSubmit.setOnClickListener(this::onClick);
        ActivityCollector.addActivity(this);
        EventBus.getDefault().registerSticky(this);
        binding.yfRecycler.setLayoutManager(new LinearLayoutManager(this));
        binding.yfRecycler.setHasFixedSize(true);
        binding.yfRecycler.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));
        adapter = new HouseSelectAdapter(new ArrayList<>(), "CHECK");
        binding.yfRecycler.setAdapter(adapter);
        adapter.setOnSelectedListiner(selectMap -> sData.add(selectMap));
        adapter.setOnRemoveListiner(map -> sData.remove(map));
        progressDialog = new ProgressDialog(this, "请稍后...");
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_submit:

                if (getIntent().hasExtra("addEnjoy")) {
                    //添加兴趣房源
                    if (sData.size() > 0 ){
                        addEnjoy(sData);
                    }else {
                        CustomToast.showToast(HasChectedActivity.this,"请选择兴趣房源",1500);
                    }
                } else {
                    if (sData.size() > 0 ){
                        EventBus.getDefault().post(sData, "TAG_FINISH_CHECKED");
                        ActivityCollector.finishAll();
                    }else {
                        CustomToast.showToast(HasChectedActivity.this,"请选择房源",1500);
                    }
                }

                break;
        }
    }

    @Subscriber(tag = "TAG_HAS_CHECKED")
    public void data(ArrayList<Map<String, Object>> data) {
        EventBus.getDefault().removeStickyEvent(data.getClass(),"TAG_HAS_CHECKED");
//        HashMap<Integer, Boolean> selectMap = new HashMap<>();
        HashSet<String> ids = new HashSet<>();
        for (int i = 0; i < data.size(); i++) {
//            selectMap.put(i, true);
            ids.add( data.get(i).get("rscode").toString() );
        }
//        adapter.setSelectMap(selectMap);
        adapter.setSelectHouseID(ids);
        adapter.setData(data);
        sData.addAll(adapter.getData());
    }

    private void addEnjoy(ArrayList<Map<String, Object>> data) {
        progressDialog.show();
        JSONArray jsonArray = new JSONArray();
        for (Map<String, Object> map : data) {
//            System.out.println( map.entrySet() );
            JSONObject object = new JSONObject();
            object.put("rsCode", map.get("rscode"));
            object.put("csCode", getIntent().getStringExtra("csCode"));
            jsonArray.add(object);
        }
        String url = "";
        if (getIntent().getStringExtra("type").equals("shs") || getIntent().getStringExtra("type").equals("sale") ) {
            url = ApiConfig.SAVE_SHS_ENJOY_HOUSE;
        } else {
            url = ApiConfig.SAVE_RENT_ENJOY_HOUSE;
        }
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonArray.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(HasChectedActivity.this, response)) {
                            CustomToast.showToast(HasChectedActivity.this, "提交成功", 1500);
//                            AppManger.getAppManager().finishActivity(AddHouseActivity.class);
                            finish();
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        ActivityCollector.removeActivity(this);
    }
}
